package PrjHttpUtils

import (
	"dgo/goutils/utils"
	"net/http"
	"time"
)

func SayHello(w http.ResponseWriter, r *http.Request) {
	AllowCrossAccessSet(w)
	str := "hello world"
	w.Write([]byte(str))
}

var (
	appinfo_funcs []func(jb *utils.JSONBuilder)
)

func OnHttpCltStatusInfo(w http.ResponseWriter, r *http.Request) {
	ResponseJSONValues(w, "host", r.Host, "timeunixsecs", time.Now().Unix(), "addr", r.RemoteAddr)
}

func OnHttpAppInfo(w http.ResponseWriter, r *http.Request) {
	var jb utils.JSONBuilder
	jb.ObjectBegin().AddValues("run-time", utils.HumanTimeStr(run_secs), "secs", run_secs)
	for _, v := range appinfo_funcs {
		v(&jb)
	}
	jb.ObjectEnd()
	w.Write(jb.Bytes())
}

func AddAppInfoOutputFunc(cb func(jb *utils.JSONBuilder)) {
	appinfo_funcs = append(appinfo_funcs, cb)
}

func RegisterHandler() {
	http.HandleFunc("/hello", WrapHandle(SayHello))
	http.HandleFunc("/proj/app/info", WrapHandle(OnHttpAppInfo))
	http.HandleFunc("/clt/status", WrapHandle(OnHttpCltStatusInfo))

	CheckDefaultConfigMonitor()
	http.HandleFunc("/monitor/status", func(writer http.ResponseWriter, request *http.Request) {
		ResponseMonitorFunc(writer, nil)
	})
}

func StartDeafultHttpFuncs() {
	RegisterHandler()
	utils.GoFunc2(RunTicker)
}
